import React, { useState, useEffect } from 'react';
import { EyeInvisibleOutlined, EyeTwoTone, MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Modal, Form, Input, Tabs, Button, InputNumber, Checkbox, message, Spin } from 'antd';
import { MailOutlined, WechatOutlined, DingdingOutlined } from '@ant-design/icons';
import { FormInstance } from 'antd/lib/form';
import { UserListItem } from '../data';
import { getUserAlert, setUserAlert } from '../service';
import styles from '../index.less';

interface CreateFormProps {
  modalVisible: boolean;
  onCancel: () => void;
  onSubmit: () => void;
  id: number;
}

const { TabPane } = Tabs;

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

const layout1 = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 16, offset: 6 },
  },
};

const formRef = React.createRef<FormInstance>();

const UserNoticeDialog: React.FC<CreateFormProps> = (props) => {
  const { modalVisible, onSubmit, onCancel, id } = props;
  const [tab, setTab] = useState<string>("1");
  const [activeKey, setActiveKey] = useState<string>("1");
  const [loading, setLoading] = useState<boolean>(false);
  const [spinning, setSpinning] = useState<boolean>(false);

  const [form] = Form.useForm();
  const [form1] = Form.useForm();
  const [form2] = Form.useForm();
  const [form3] = Form.useForm();
  const [form4] = Form.useForm();

  useEffect(() => {
    if (modalVisible) {
      const weChatUserIdsEmpty = [{
        fieldKey: 0,
        isListField: true,
        key: 0,
        name: 0,
        wechatUserId: "",
      }];
      const alertEmailToEmpty = [{
        fieldKey: 0,
        isListField: true,
        key: 0,
        name: 0,
        alertEmailTo: "",
      }];
      if (id) {
        setTab("1");
        setSpinning(true);
        new Promise((resolve, reject) => {
          getUserAlert(id)
            .then((res) => {
              if (res.code === 200) {
                const data = res.data;
                //报警邮箱初始化
                const alertEmailServer = data.alertEmailServer;
                if (alertEmailServer) {
                  const alertEmailTos = new Array();
                  data.alertEmailTo.split(',').map((item, index) => {
                    let temp = new Object;
                    temp["isListField"] = true;
                    temp["fieldKey"] = index;
                    temp["key"] = index;
                    temp["name"] = index;
                    temp["alertEmailTo"] = item;
                    alertEmailTos.push(temp);
                  });
                  data.alertEmailTo = alertEmailTos;
                  form.setFieldsValue(data);
                } else {
                  form.resetFields();
                  form.setFieldsValue({
                    alertEmailTo: alertEmailToEmpty,
                  });
                }
                form.setFieldsValue({ "userId": id });
                //企业微信--应用发送初始化
                if (data.wechatCompanyId) {
                  const wechatUserId = data.wechatUserId.split(",");
                  const wechatUserIds = new Array();
                  wechatUserId.map((item, index) => {
                    let temp = new Object;
                    temp["isListField"] = true;
                    temp["fieldKey"] = index;
                    temp["key"] = index;
                    temp["name"] = index;
                    temp["wechatUserId"] = item;
                    wechatUserIds.push(temp);
                  });
                  data.wechatUserId = wechatUserIds;
                  form1.setFieldsValue(data);
                } else {
                  form1.resetFields();
                  form1.setFieldsValue({
                    wechatUserId: weChatUserIdsEmpty,
                  });
                }
                form1.setFieldsValue({ "userId": id });
                //企业微信--群组发送初始化
                if (data.wechatWebHook) {
                  form2.setFieldsValue(data);
                } else {
                  form2.resetFields();
                }
                form2.setFieldsValue({ "userId": id });
                //钉钉初始化
                if (data.dingdingWebHook) {
                  form3.setFieldsValue(data);
                } else {
                  form3.resetFields();
                }
                form3.setFieldsValue({ "userId": id });
                //通知时间
                if (data.expireTime) {
                  data.alertTriggerHour = parseInt(data.expireTime.split(":")[0]);
                  data.alertTriggerMinute = parseInt(data.expireTime.split(":")[1]);
                  form4.setFieldsValue(data);
                } else {
                  form4.resetFields();
                }

                resolve(true);
              } else {
                message.error('请求失败，' + res.message);
                resolve(false);
              }
              setSpinning(false);
            })
            .catch((error) => {
              setSpinning(false);
              message.error('请求失败');
              reject(error);
            });
        });
      }
    }
  }, [modalVisible]);

  const formValuesFormat = () => {
    const values = new Object as UserListItem;
    const values1 = form.getFieldsValue();
    const values2 = form1.getFieldsValue();
    const values3 = form2.getFieldsValue();
    const values4 = form3.getFieldsValue();
    if (values1.alertEmailServer) {
      values1.alertEmailUsername = values1.alertEmailFrom.split("@")[0];
      const alertEmailTo = new Array();
      values1.alertEmailTo.map((item, index) => {
        alertEmailTo.push(item.alertEmailTo)
      });
      values1.alertEmailTo = alertEmailTo.toString();
      for (var key in values1) {
        values[key] = values1[key];
      }
    }
    if (values2.wechatCompanyId) {
      const wechatUserId = new Array();
      values2.wechatUserId.map((item, index) => {
        wechatUserId.push(item.wechatUserId)
      });
      values2.wechatUserId = wechatUserId.toString();
      for (var key in values2) {
        values[key] = values2[key];
      }
    }
    if (values3.wechatWebHook) {
      for (var key in values3) {
        values[key] = values3[key];
      }
    }
    if (values4.dingdingWebHook) {
      for (var key in values4) {
        values[key] = values4[key];
      }
    }
    const alertTriggerHour = form4.getFieldValue("alertTriggerHour");
    const alertTriggerMinute = form4.getFieldValue("alertTriggerMinute");
    values.expireTime = (alertTriggerHour > 9 ? alertTriggerHour : `0${alertTriggerHour}`) + ":" + alertTriggerMinute;
    console.log(values);
    setLoading(true);
    new Promise((resolve, reject) => {
      setUserAlert(values)
        .then((res) => {
          setLoading(false);
          if (res.code === 200) {
            message.success('设置成功');
            onSubmit();
            resolve(true);
          } else {
            message.error('请求失败，' + res.message);
            resolve(false);
          }
        })
        .catch((error) => {
          setLoading(false);
          message.error('请求失败');
          reject(error);
        });
    });
  }

  // const formCheck = async () => {
  //   const messageArray = ['报警邮箱', '企业微信-应用发送', '企业微信-群组发送', '钉钉'];
  //   const list = [form, form1, form2, form3];
  //   function startCheck() {
  //     //定义counts，用来收集请求的次数，（也可以用resList的length进行判断）
  //     let counts = 0;
  //     return function requestFunc() {
  //       if (counts == list.length) {
  //         console.log("验证执行结束")
  //         formValuesFormat();
  //         return;
  //       }
  //       let a = new Promise((res, rej) => {
  //         const formItem = list[counts];
  //         formItem.validateFields()
  //           .then(result => {
  //             res(true)
  //             console.log('Success:', counts);
  //           })
  //           .catch((error) => {
  //             console.log('error', counts);
  //             message.error(messageArray[counts] + ' 页面信息填写有误');
  //             rej(error);
  //           });
  //       })
  //       //无论成功或者失败都要进行下一次，以免阻塞，成功请求的末尾有s标志，失败的末尾有f标志
  //       a.then(() => {
  //         counts++;
  //         requestFunc();
  //       }).catch(err => {
  //         console.log('error', counts);
  //         // message.error(messageArray[counts]+'页面信息填写有误');
  //       })
  //     }
  //   }
  //   let start = startCheck();
  //   start();
  // }

  const handleSubmit = () => {
    // if (JSON.stringify(form.getFieldsValue()) == "{}"
    //   || JSON.stringify(form1.getFieldsValue()) == "{}"
    //   || JSON.stringify(form2.getFieldsValue()) == "{}"
    //   || JSON.stringify(form3.getFieldsValue()) == "{}") {
    //   Modal.warn({
    //     title: '请完善其他页面配置信息',
    //     content: '',
    //     okText: '知道了',
    //   });
    //   return;
    // }
    // formCheck();
    formValuesFormat();
  };

  const setScroll = () => {
    setTimeout(function () {
      const body = document.getElementsByClassName("wechatUserId")[0];
      const height = body?.querySelector('.content')?.clientHeight;
      if (height && height > 160) {
        body.scrollTop = height;
      }
    }, 0)
  }

  const handleUpdate = () => {
    if (tab == "1") {
      if (!form) return;
      form.submit();
    } else if (tab == "2") {
      if (activeKey == "3") {
        if (!form1) return;
        form1.submit();
      } else if (activeKey == "4") {
        if (!form2) return;
        form2.submit();
      }
    } else if (tab == "5") {
      if (!form3) return;
      form3.submit();
    }
  };

  const callback = (key: string) => {
    if (key == "2") {
      setActiveKey("3");
    }
    setTab(key);
  }

  const callback1 = (key: string) => {
    setActiveKey(key);
  }

  const modalFooter = { okText: '保存', onOk: handleUpdate, onCancel: onCancel };

  const IsURL = (str_url: string) => {
    var strRegex = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
    var re = new RegExp(strRegex);
    if (re.test(str_url)) {
      return (true);
    } else {
      return (false);
    }
  }
  const sslChange = (e: Event) => {
    const value = e.target.checked;
    form.setFieldsValue({ "alertEmailSslEnable": value })
  }
const emailEnabledChange = (e:Event)=>{
  const value = e.target.checked;
  form.setFieldsValue({ "emailEnabled": value })
}
const wechatUserEnabledChange = (e:Event)=>{
  const value = e.target.checked;
  form.setFieldsValue({ "wechatUserEnabled": value })
}
const wechatGroupEnabledChange = (e:Event)=>{
  const value = e.target.checked;
  form.setFieldsValue({ "wechatGroupEnabled": value })
}
const dingdingEnabledChange = (e:Event)=>{
  const value = e.target.checked;
  form.setFieldsValue({ "dingdingEnabled": value })
}
  const renderContent = () => {
    return (
      <>
        <Tabs onChange={callback} type="card">
          <TabPane tab={<span><MailOutlined />报警邮箱</span>} key="1">
            <Form {...layout} ref={formRef} form={form} onFinish={handleSubmit}>
              <Form.Item name="userId" style={{ display: 'none' }}></Form.Item>
              <Form.Item
                name="alertEmailServer"
                label="服务器地址"
                rules={[{ required: true, max: 64 }]}
              >
                <Input placeholder="请输入服务器地址" />
              </Form.Item>
              <Form.Item
                name="alertEmailPort"
                label="端口号"
                rules={[{ required: true }]}
              >
                <InputNumber min={0} max={65535} defaultValue={0} placeholder="请输入服务器端口号" />
              </Form.Item>
              <Form.Item
                name="alertEmailFrom"
                label="发件人邮箱地址"
                rules={[{ required: true, max: 64, type: "email" }]}
              >
                <Input placeholder="请输入发件人邮箱地址" />
              </Form.Item>
              <Form.Item
                name="alertEmailUsername"
                label="邮箱用户名"
                hidden={true}
              >
                <Input placeholder="请输入邮箱用户名" />
              </Form.Item>
              <Form.Item
                name="alertEmailPassword"
                label="邮箱授权码"
                rules={[{ required: true, max: 64 }]}
              >
                <Input.Password
                  placeholder="请输入邮箱授权码"
                  iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                  style={{ width: 'calc(100% - 30px)' }}
                  autoComplete="new-password"
                />
              </Form.Item>
              <Form.Item
                name="alertEmailSslEnable"
                label="是否启用SSL"
                initialValue={false}
                valuePropName="checked"
              >
                <Checkbox onChange={sslChange}>启用</Checkbox>
              </Form.Item>
              <Form.Item
                name="emailEnabled"
                label="通知是否启用"
                initialValue={false}
                valuePropName="checked"
              >
                <Checkbox onChange={emailEnabledChange}>启用</Checkbox>
              </Form.Item>
              <hr />
              <Form.List
                name="alertEmailTo"
              >
                {(fields, { add, remove }) => (
                  <>
                    <span className="wechatUserId">
                      <div className="content">
                        {fields.map((field, index) => (
                          <Form.Item
                            {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
                            label={index === 0 ? '收件人邮箱地址' : ''}
                            required={true}
                            key={field.key}
                          >
                            <Form.Item
                              {...field}
                              name={[field.name, 'alertEmailTo']}
                              fieldKey={[field.fieldKey, 'alertEmailTo']}
                              rules={[{ type: 'email', message: '收件人邮箱地址不是一个有效的email' }, {
                                validator: (rule, value, callback) => {
                                  if (!value) {
                                    callback("请输入收件人邮箱地址");
                                    return;
                                  }
                                  if (value.length > 64) {
                                    callback("收件人邮箱地址最多64个字符");
                                  } else {
                                    callback();
                                  }
                                },
                              }
                              ]}
                              noStyle
                            >
                              <Input placeholder="请输入收件人邮箱地址" />
                            </Form.Item>
                            {fields.length > 1 ? (
                              <MinusCircleOutlined
                                className="deleteButton"
                                onClick={() => { remove(field.name) }}
                              />
                            ) : null}
                          </Form.Item>
                        ))}
                      </div>
                    </span>
                    <Form.Item {...formItemLayoutWithOutLabel}>
                      <Button
                        type="dashed"
                        onClick={() => {
                          add();
                          setScroll();
                        }}
                        icon={<PlusOutlined />}
                      >
                        添加收件人邮箱地址
                      </Button>
                    </Form.Item>
                  </>
                )}
              </Form.List>
            </Form>
          </TabPane>
          <TabPane tab={<span><WechatOutlined />企业微信</span>} key="2">
            <Tabs activeKey={activeKey} onChange={callback1} type="card">
              <TabPane tab="应用发送" key="3">
                <Form {...layout} ref={formRef} form={form1} onFinish={handleSubmit}>
                  <Form.Item name="userId" style={{ display: 'none' }}></Form.Item>
                  <Form.Item
                    name="wechatCompanyId"
                    label="企业ID"
                    rules={[{ required: true, max: 64, whitespace: true }]}
                  >
                    <Input placeholder="请输入企业ID" />
                  </Form.Item>
                  <Form.Item
                    name="wechatAppId"
                    label="应用ID"
                    rules={[{
                      required: true,
                      pattern: /(^[1-9]\d*$)/,
                      whitespace: true,
                      message: '必须为正整数'
                    }]}
                  >
                    <Input placeholder="请输入应用ID" maxLength={16} />
                  </Form.Item>
                  <Form.Item
                    name="wechatAppSecret"
                    label="应用secret"
                    rules={[{ required: true, max: 64, whitespace: true }]}
                  >
                    <Input placeholder="请输入应用secret" />
                  </Form.Item>
                  <Form.List
                    name="wechatUserId"
                  >
                    {(fields, { add, remove }) => (
                      <>
                        <span className="wechatUserId">
                          <div className="content">
                            {fields.map((field, index) => (
                              <Form.Item
                                {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
                                label={index === 0 ? '用户ID' : ''}
                                required={true}
                                key={field.key}
                              >
                                <Form.Item
                                  {...field}
                                  name={[field.name, 'wechatUserId']}
                                  fieldKey={[field.fieldKey, 'wechatUserId']}
                                  rules={[{
                                    validator: (rule, value, callback) => {
                                      if (!value) {
                                        callback("请输入用户ID");
                                        return;
                                      }
                                      if (value.length > 64) {
                                        callback("用户ID最多64个字符");
                                      } else {
                                        callback();
                                      }
                                    },
                                  }
                                  ]}
                                  noStyle
                                >
                                  <Input placeholder="请输入用户ID" />
                                </Form.Item>
                                {fields.length > 1 ? (
                                  <MinusCircleOutlined
                                    className="deleteButton"
                                    onClick={() => { remove(field.name) }}
                                  />
                                ) : null}
                              </Form.Item>
                            ))}
                          </div>
                        </span>
                        <Form.Item {...formItemLayoutWithOutLabel}>
                          <Button
                            type="dashed"
                            onClick={() => {
                              add();
                              setScroll();
                            }}
                            icon={<PlusOutlined />}
                          >
                            添加用户ID
                          </Button>
                        </Form.Item>
                      </>
                    )}
                  </Form.List>
                  <Form.Item
                    name="wechatUserEnabled"
                    label="通知是否启用"
                    initialValue={false}
                    valuePropName="checked"
                  >
                    <Checkbox onChange={wechatUserEnabledChange}>启用</Checkbox>
                  </Form.Item>
                </Form>
              </TabPane>
              <TabPane tab="群组发送" key="4">
                <Form {...layout1} ref={formRef} form={form2} onFinish={handleSubmit}>
                  <Form.Item name="userId" style={{ display: 'none' }}></Form.Item>
                  <Form.Item
                    name="wechatWebHook"
                    label="机器人webhook地址"
                    rules={[{ required: true, max: 256 }, {
                      validator: (rule, value, callback) => {
                        if (!value) {
                          callback();
                        }
                        if (IsURL(value)) {
                          callback();
                        } else {
                          callback("不是一个有效的地址");
                        }
                      },
                    }]}
                  >
                    <Input placeholder="请输入机器人webhook地址" />
                  </Form.Item>
                  <Form.Item
                    name="wechatGroupEnabled"
                    label="通知是否启用"
                    initialValue={false}
                    valuePropName="checked"
                  >
                    <Checkbox onChange={wechatGroupEnabledChange}>启用</Checkbox>
                  </Form.Item>
                </Form>
              </TabPane>
            </Tabs>
          </TabPane>
          <TabPane tab={<span><DingdingOutlined />钉钉</span>} key="5">
            <Form {...layout1} ref={formRef} form={form3} onFinish={handleSubmit}>
              <Form.Item name="userId" style={{ display: 'none' }}></Form.Item>
              <Form.Item
                name="dingdingWebHook"
                label="机器人webhook地址"
                rules={[{ required: true, max: 256 }, {
                  validator: (rule, value, callback) => {
                    if (!value) {
                      callback();
                    }
                    if (IsURL(value)) {
                      callback();
                    } else {
                      callback("不是一个有效的地址");
                    }
                  },
                }]}
              >
                <Input placeholder="请输入机器人webhook地址" />
              </Form.Item>
              <Form.Item
                name="dingdingEnabled"
                label="通知是否启用"
                initialValue={false}
                valuePropName="checked"
              >
                <Checkbox onChange={dingdingEnabledChange}>启用</Checkbox>
              </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
        <Form {...layout} ref={formRef} form={form4} >
          <Form.Item
            name="expireTime"
            label="通知时间"
            initialValue={false}
            style={{ marginBottom: 0 }}
          >
            <Form.Item noStyle name="alertTriggerHour" initialValue={0}>
              <InputNumber
                min={0}
                max={23}
                defaultValue={0}
                formatter={value => value > 9 ? value : `0${value}`}
                style={{ width: 60 }}
              />
            </Form.Item>
            <Form.Item noStyle name="alertTriggerMinute" initialValue={15}>
              <InputNumber min={15} max={55} defaultValue={15} style={{ width: 60,marginLeft:-1 }} />
            </Form.Item>
          </Form.Item>
        </Form>
      </>
    );
  };

  return (
    <Modal
      className={styles.emailSetDialog}
      confirmLoading={loading}
      destroyOnClose
      title="用户异常通知设置"
      visible={modalVisible}
      {...modalFooter}
    >
      <Spin spinning={spinning}>
        {renderContent()}
      </Spin>
    </Modal>
  );
};

export default UserNoticeDialog;
